<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="nav">
        <button id="news">新闻</button>
        <button id="hao" >hao123</button>
        <button id="map">地图</button>
    </div>
    <div id="content"></div>
    <script>
        document.getElementById("news").addEventListener("click",function(e){
            history.pushState({},"","/news");
        })
        document.getElementById("hao").addEventListener("click",function(e){
            history.pushState({},"","/hao");
        })
        document.getElementById("map").addEventListener("click",function(e){
            history.pushState({},"","/map");
        })
        // 重写 pushState 方法，才能够达到当 url发生变化的时候，触发自定义事件
        let originalPushState = history.pushState;
        history.pushState = function(state,title,url){
            // 添加自定义的处理逻辑上去
            
            switch(url){
                case "/news":
                    document.getElementById("content").innerHTML = "新闻";
                    break;
                case "/hao":
                    document.getElementById("content").innerHTML = "好";
                break;
                case "/map":
                    document.getElementById("content").innerHTML = '地图';
                break;
            }
            originalPushState.call(this,state,title,url);
        }
        window.addEventListener("popstate",function(){
            console.log("前进和后退");
        })
    </script>
</body>

</html>